package com.utils.httphelper;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class DownloadUtil {
	private static final Logger logger = LoggerFactory.getLogger(DownloadUtil.class);

	public static void main(String[] args) {
//		DownloadUtil.downFile();
//		Map<String,String> map = Maps.newHashMap();
//		map.put("https://qnunion.feierlaiedu.com/1083341-1594742174130-playback.mp4", "D:\\playback1.mp4");
//		map.put("https://qnunion.feierlaiedu.com/1084516-1594830836042-playback.mp4", "D:\\playback2.mp4");
//		map.put("https://qnunion.feierlaiedu.com/1082058-1594649673556-playback.mp4", "D:\\playback3.mp4");
//		map.put("https://qnunion.feierlaiedu.com/1085630-1594915827735-playback.mp4", "D:\\playback4.mp4");
//		map.put("https://qnunion.feierlaiedu.com/1087071-1595007055671-playback.mp4", "D:\\playback5.mp4");
//		map.put("https://res1.eqh5.com/Fgo-nXcidd1vUTpW96Lr5MIWbBaC?imageMogr2/auto-orient%7CimageMogr2/auto-orient/crop/!656x280a0a0%7CimageMogr2/auto-orient/thumbnail/754x322%3E/format/webp", "D:\\hdfk.gif");
//		
//		//System.out.println(System.currentTimeMillis());
//		
//		for (Entry<String,String> entry : map.entrySet()) {
//			downloadImg(entry.getKey(),entry.getValue());
//		}
		
		String url = "https://res1.eqh5.com/Fgo-nXcidd1vUTpW96Lr5MIWbBaC";
		String filename = "D:\\hdfk.gif";
		downloadImg(url,filename);

//		Map<String, Object> headerMap = Maps.newHashMap();
//		// headerMap.put("ETag", "5b2a5ce1-19de8");
//		// headerMap.put("Last-Modified", new Date().toString());
//		headerMap.put("Cache-Control", "max-age=0");
//		headerMap.put("Referer", "http://www.mm131.com/xinggan/4086_2.html");
//		headerMap.put("User-Agent",
//				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36");
//		headerMap.put("Accept",
//				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
//		headerMap.put("Accept-Encoding", "gzip, deflate");
//		headerMap.put("Accept-Language", "zh-CN,zh;q=0.9");
//		headerMap.put("Connection", "keep-alive");
//		// headerMap.put("Host", "mg1.mm131.mei");
//		headerMap.put("Upgrade-Insecure-Request", "1");
//		loadFileFromURL("http://img1.mm131.me/pic/4051/0.jpg", "D:\\sese\\ww.jpg", headerMap);
		// loadFileFromURL("http:"+"//pic.qiushibaike.com/system/pictures/12012/120122767/medium/app120122767.jpg","D:\\sese\\1234.jpg",headerMap);
	}

//	public static void downFile() {
//		Map<String,String> map = Maps.newHashMap();
//
//		String urlpath1 = "http://mreport.kyhddsp.com/report/detail_excel?bdate=%s&edate=%s&adver=&media=aszs&appid=448165862";
//		for (int i = 1; i <=31 ; i++) {
//			if(i==31) {
//				map.put("D:\\momo\\"+i+".xls", String.format(urlpath1, "2019-05-31", "2019-06-01"));	
//			}else {
//				String date = i+"";
//				if(i<10) {
//					date = "0"+i;
//				}
//				String afterdate = (i+1)+"";
//				if((i+1)<10) {
//					afterdate = "0"+(i+1);
//				}
//				date = "2019-05-"+date;
//				afterdate = "2019-05-"+afterdate;
//				map.put("D:\\momo\\"+i+".xls", String.format(urlpath1, date, afterdate));	
//			}
//		}
//		for (String name : map.keySet()) {
//			String url = map.get(name);
//			System.out.println(url);
//			 downloadImg(url,name);
//		}
//	}
	
	/**
	 * 实现网络访问文件，将获取到的数据保存在指定目录中
	 * 
	 * @param url
	 *            访问网络的url地址
	 * @param destFile
	 *            保存的文件
	 * @return
	 */
	public static boolean loadFileFromURL(String url, String filePath, Map<String, Object> headerMap) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet requestGet = new HttpGet(url);
		HttpResponse httpResponse = null;
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			// 创建本地文件路径
			File file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			bos = new BufferedOutputStream(new FileOutputStream(file));
			if (headerMap != null) {
				for (String key : headerMap.keySet()) {
					requestGet.setHeader(key, headerMap.get(key).toString());
				}
			}

			httpResponse = httpClient.execute(requestGet);
			if (httpResponse.getStatusLine().getStatusCode() == 200
					|| httpResponse.getStatusLine().getStatusCode() == 304) {
				HttpEntity entity = httpResponse.getEntity();
				bis = new BufferedInputStream(entity.getContent());
				int len = -1;
				byte[] buffer = new byte[8 * 1024];
				while ((len = bis.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
					bos.flush();
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}

	// 下载指定路径图片
	public static boolean downloadImg(String netImg, String filePath) {
/*		while(m.find()){
			Files.copy(new URL(m.group(1)).openStream(), Paths.get(out + UUID.randomUUID() + ".jpg"));*/
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		// 第一步，创建网络连接
		try {
			URL url = new URL(netImg);
			// 第二步，打开连接
			URLConnection urlconnection = url.openConnection();
			// 第三步，获取流对象
			bis = new BufferedInputStream(urlconnection.getInputStream());
			// 第四步，创建本地文件路径
			File file = new File(filePath);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			// 第五步，下载
			bos = new BufferedOutputStream(new FileOutputStream(file));

			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len = bis.read(buffer)) != -1) {
				bos.write(buffer, 0, len);
				bos.flush();
			}

			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			// 第六步，关闭IO
			try {
				if (bos != null)
					bos.close();
			} catch (IOException e) {
			}
			try {
				if (bis != null)
					bis.close();
			} catch (IOException e) {
			}
		}
	}

	
	/**
	 * 从网络上下载图片
	 */
	public static void downloadPicture(String url, String dirPath,
			String filePath) {
		
		DefaultHttpClient httpclient = new DefaultHttpClient();
		
		HttpGet httpget = new HttpGet(url);
 
		httpget
				.setHeader(
						"User-Agent",
						"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
		httpget
				.setHeader("Accept",
						"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
 
		try {
			HttpResponse resp = httpclient.execute(httpget);
			if (HttpStatus.SC_OK == resp.getStatusLine().getStatusCode()) {
				HttpEntity entity = resp.getEntity();
 
				InputStream in = entity.getContent();
 
				savePicToDisk(in, dirPath, filePath);
				
				System.out.println("保存图片 "+filePath+" 成功....");
			}
 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
	}
 
	/**
	 * 将图片写到 硬盘指定目录下
	 * @param in
	 * @param dirPath
	 * @param filePath
	 */
	private static void savePicToDisk(InputStream in, String dirPath,
			String filePath) {
 
		try {
			File dir = new File(dirPath);
			if (dir == null || !dir.exists()) {
				dir.mkdirs();
			}
 
			//文件真实路径
			String realPath = dirPath.concat(filePath);
			File file = new File(realPath);
			if (file == null || !file.exists()) {
				file.createNewFile();
			}
 
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = in.read(buf)) != -1) {
				fos.write(buf, 0, len);
			}
			fos.flush();
			fos.close();
 
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
	/**
	 * 将入库的文本段子做个本地备份
	 * 
	 * @param map
	 */
	public static void writeTxT(String path, Object[] txt) {

		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(path, true));// 追加形式
			for (Object str : txt) {
				out.write(str.toString() + "\r\n");
			}
			logger.info("写入本地 " + path + "完毕");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} // 把缓存区内容压入文件
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			} // 最后记得关闭文件
		}
	}

	/**
	 * 将入库的热门,趣图,短视频做个本地备份
	 * 
	 * @param map
	 */
	public static void writeImage(String path, Map<String, String> hotMap) {

		BufferedWriter out = null;
		try {
			out = new BufferedWriter(new FileWriter(path, true));// 追加形式
			for (String str : hotMap.keySet()) {
				if (!"".equals(str.trim())) {
					out.write(str + "\r\n");// \r\n即为换行
					out.write(hotMap.get(str) + "\r\n");
				}
			}
			logger.info("写入本地 " + path + "完毕");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
			} catch (IOException e) {
				e.printStackTrace();
			} // 把缓存区内容压入文件
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			} // 最后记得关闭文件
		}
	}

	// 获取网页源代码
	public static String htmlSource(String link, String encoding) {
		StringBuilder stringBuilder = new StringBuilder();
		// 1，创建连接
		try {
			URL url = new URL(link);
			// 2，打开连接
			URLConnection urlConnection = url.openConnection();
			// 3，打开流
			InputStream inputStream = urlConnection.getInputStream();
			// 4,利用转换流将字节流转换为字符流，并存入缓冲区
			InputStreamReader isr = new InputStreamReader(inputStream, encoding);
			BufferedReader bufferedReader = new BufferedReader(isr);
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				stringBuilder.append(line + "\r\n");
			}
			// 5,关闭
			bufferedReader.close();
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stringBuilder.toString();
	}
}